<template>
	<view class="page" :data-theme="theme">
		<view class="system-height" :style="{height:statusBarHeight}"></view>
		<view class="title-bar" style="height: 43px;">
			<view class="icon" @click="back" v-if="!isHome">
				<image src="https://lives-1308318918.cos.ap-shanghai.myqcloud.com/usr/left.png"></image>
			</view>
			<view class="icon" @click="home" v-else>
				<image src="https://lives-1308318918.cos.ap-shanghai.myqcloud.com/usr/home.png"></image>
			</view>
			账户登录
		</view>
		<form @submit="formSubmit" report-submit='true'>

			<view class="wechat_login">
				<view class="img">
					<image src="https://lives-1308318918.cos.ap-shanghai.myqcloud.com/usr/wechat_login.png"
						mode="widthFix">
					</image>
				</view>
				<view class="item acea-row row-between-wrapper">
					<view>用户头像</view>
					<button class="pictrue" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
						<image :src='userInfo.avatarUrl'></image>
						<image :src='editPng' class="alter"></image>
					</button>
				</view>
				<view class='item acea-row row-between-wrapper'>
					<view>用户姓名</view>
					<view class='input'>
						<input type='text' v-model='userInfo.nickname' placeholder="输入昵称" maxlength="20" />
					</view>
				</view>

				<view class='item acea-row row-between-wrapper' @click="openRole">
					<view>角色信息</view>
					<view class="input">
						<view class="input">
							<text>{{userInfo.roleName}}</text>
							<text class="iconfont icon-xiangyou"></text>
						</view>
					</view>
				</view>

				<view class="btn-wrapper">
					<button hover-class="none" open-type="getPhoneNumber" @getphonenumber="getphonenumber"
						class="bg-green btn1">微信注册</button>
					<!-- <button hover-class="none" @click="isUp = true" class="btn2">验证码登录</button> -->
				</view>
			</view>
		</form>


		<picker-data ref="picker" title="选择角色" :picker="localData" label="roleName" v-if="pickerShow"
			@sure="sureData"></picker-data>
	</view>
</template>

<script>
	const app = getApp();
	let statusBarHeight = uni.getSystemInfoSync().statusBarHeight + 'px';
	import pickerData from "@/components/pickerData/index"
	import {
		mapGetters
	} from "vuex";
	import {
		getLogo,
		getUserPhone
	} from '@/api/public';
	import {
		LOGO_URL,
		EXPIRES_TIME,
		USER_INFO,
		STATE_R_KEY
	} from '@/config/cache';
	import {
		getRole,
		getUserInfo,
		spread
	} from '@/api/user.js'
	import {
		uploadFiles
	} from "@/utils/index.js"
	import Routine from '@/libs/routine';
	import wechat from "@/libs/wechat";
	export default {
		data() {
			return {
				localData: [],
				isUp: false,
				phone: '',
				statusBarHeight: statusBarHeight,
				isHome: false,
				isPhoneBox: false,
				logoUrl: '',
				code: '',
				authKey: '',
				options: '',
				userInfo: {
					avatarUrl: "",
					nickname: "",
					roleRequestId: "",
					roleName: "家长",
					id: 0
				},
				pickerShow: false,
				codeNum: 0,
				theme: app.globalData.theme,
				getPhoneContent: '申请获取您的手机号用于注册，完成后可使用商城更多功能',
				editPng: 'https://lives-1308318918.cos.ap-shanghai.myqcloud.com/images/alert1.png'

			}
		},
		components: {
			pickerData
		},
		onLoad(options) {

			getLogo().then(res => {
				this.logoUrl = res.data.logoUrl
			})

			getRole().then(res => {
				this.localData = res.data.filter(item => item.id > 5);
				this.localData.unshift({id: 0, roleName: "家长"});
				console.error(res.data);
			})
		},
		methods: {
			sureData(e) {
				this.userInfo.roleName = e.roleName;
				this.userInfo.roleRequestId = e.id;
			},

			valueChange(e) {
				console.log(e);
			},
			//角色信息选择
			openRole() {
				this.pickerShow = true;
				this.$nextTick(() => {
					this.$refs.picker.show();
				})
			},

			onChooseAvatar(e) {
				const {
					avatarUrl
				} = e.detail
				this.m_show("上传中");
				uploadFiles(avatarUrl).then(res => {
					this.userInfo.avatarUrl = res;
					this.m_hide();
				})
			},

			back() {
				uni.navigateBack();
			},
			home() {
				uni.switchTab({
					url: '/pages/home/home'
				})
			},
			modelCancel() {
				this.isPhoneBox = false;
			},
			// 弹窗关闭
			maskClose() {
				this.isUp = false //点击模态框会关闭登录弹框，防止用户误触而关闭
			},
			bindPhoneClose(data) {
				if (data.isStatus) {
					this.isPhoneBox = false
					this.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				} else {
					this.isPhoneBox = false
				}
			},
			// #ifdef MP
			/**
			 * 获取个人用户信息
			 */
			getUserInfo: function() {
				let that = this;
				getUserInfo().then(res => {
					uni.hideLoading();
					that.userInfo = res.data
					that.$store.commit("UPDATE_USERINFO", res.data);
					that.$util.Tips({
						title: '登录成功',
						icon: 'success'
					}, {
						tab: 3
					})
				});
			},

			getphonenumber(e) {
				// if (this.m_empty(this.userInfo.nickname)) {
				// 	return this.m_toast("请输入用户姓名");
				// }
				// if (this.m_empty(this.userInfo.avatarUrl)) {
				// 	return this.m_toast("请选择用户头像");
				// }
				uni.showLoading({
					title: '加载中'
				});
				Routine.getCode().then(code => {
					this.getUserPhoneNumber(e.detail.encryptedData, e.detail.iv, code);
				}).catch(error => {
					uni.hideLoading();
				});
			},
			// 小程序获取手机号码回调
			getUserPhoneNumber(encryptedData, iv, code) {
				let self = this;
				self.getWxUser({
					encryptedData: encryptedData,
					iv: iv,
					code: code,
					type: 'routine'
				})
			},

			getWxUser(userInfo) {
				let self = this
				userInfo.spread_spid = app.globalData.spread; //获取推广人ID
				userInfo.avatar = this.userInfo.avatarUrl;
				userInfo.country = "CN";
				userInfo.nickName = this.userInfo.nickname;
				userInfo.sex = 0;
				userInfo.type = 'routine'
				userInfo.roleName = this.userInfo.roleName;
				userInfo.roleRequestId = this.userInfo.roleRequestId;
				Routine.authUserInfo(userInfo.code, userInfo)
					.then(res => {
						self.authKey = res.data.key;
						if (res.data.type === 'register') {
							uni.hideLoading();
							userInfo.key = res.data.key;
							self.putData(userInfo);
						}
						if (res.data.type === 'login') {
							uni.hideLoading();
							self.$store.commit('LOGIN', {
								token: res.data.token
							});
							self.$store.commit("SETUID", res.data.uid);
							self.getUserInfo();
							//登陆成功后读取spread绑定分销关系
							if (app.globalData.spread) {
								spread(app.globalData.spread).then(res => {}) 
							}
							self.$util.Tips({
								title: res,
								icon: 'success'
							}, {
								tab: 3
							})
						}
					}).catch(res => {
						uni.hideLoading();
						uni.showToast({
							title: res,
							icon: 'none',
							duration: 2000
						});
					});
			},

			putData(userInfo) {
				userInfo["key"] = this.authKey;
				Routine.getCode()
					.then(code => {
						userInfo.code = code;
						getUserPhone(userInfo).then(res => {
							this.$store.commit('LOGIN', {
								token: res.data.token
							});
							this.$store.commit("SETUID", res.data.uid);
							this.getUserInfo();
						}).catch(res => {
							uni.hideLoading();
							this.$util.Tips({
								title: res
							});
							console.error(res);
						});
				}).catch(error => {
					uni.hideLoading();
				});
			},

			// #endif
			// #ifdef H5
			// 获取url后面的参数
			getQueryString(name) {
				var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
				var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
				var r = window.location.search.substr(1).match(reg);
				var q = window.location.pathname.substr(1).match(reg_rewrite);
				if (r != null) {
					return unescape(r[2]);
				} else if (q != null) {
					return unescape(q[2]);
				} else {
					return null;
				}
			},
			// 公众号登录
			wechatLogin() {
				if (!this.code && this.options.scope !== 'snsapi_base') {
					this.$wechat.oAuth('snsapi_userinfo', '/pages/users/wechat_login/index');
				} else {
					// if (this.authKey) {
					// 	this.isUp = true;
					// }
					this.isUp = true;
				}
			},
			// 输入手机号后的回调
			wechatPhone() {
				this.$Cache.clear('snsapiKey');
				if (this.options.back_url) {
					let url = uni.getStorageSync('snRouter');
					url = url.indexOf('/pages/home/home') != -1 ? '/' : url;
					if (url.indexOf('/pages/users/wechat_login/index') !== -1) {
						url = '/';
					}
					if (!url) {
						url = '/pages/home/home';
					}
					this.isUp = false
					uni.showToast({
						title: '登录成功',
						icon: 'none'
					})
					setTimeout(res => {
						location.href = url
					}, 800)
				} else {
					uni.navigateBack()
				}
			}
			// #endif
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #fff;
		height: 100%;
	}

	.page {
		background: #fff;
		height: 100%;
	}

	.item {
		width: 690rpx;
		height: 120rpx;
		background-color: #f8f8f8;
		border-radius: 20rpx;
		margin-bottom: 22rpx;
		padding: 0 30rpx;
		position: relative;
		border: 2rpx solid #f8f8f8;
		box-sizing: border-box;

		.input {
			width: 415rpx;
			text-align: right;
			color: #868686;
		}
	}

	.pictrue {
		width: 96rpx;
		height: 96rpx;
		position: relative;

		.alter {
			width: 30rpx;
			height: 30rpx;
			border-radius: 50%;
			position: absolute;
			bottom: 0;
			right: 0;
		}
	}

	.pictrue image {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}


	.wechat_login {
		padding: 42rpx 34rpx;

		.img {
			text-align: center;
			margin-top: 50rpx;

			image {
				width: 80%;
			}
		}

		.btn-wrapper {
			margin-top: 100rpx;
			padding: 0 66rpx;

			button {
				width: 100%;
				height: 86rpx;
				line-height: 86rpx;
				margin-bottom: 40rpx;
				border-radius: 20rpx;
				font-size: 35rpx;

				&.btn1 {
					color: #fff;
					background-color: #007E51;
				}

				&.btn2 {
					color: #007E51;
					border-color: #007E51;
					border: 1px solid #666666;
				}
			}
		}
	}

	.title-bar {
		position: relative;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 36rpx;
	}

	.icon {
		position: absolute;
		left: 30rpx;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 86rpx;
		height: 86rpx;

		image {
			width: 50rpx;
			height: 50rpx;
		}
	}
</style>